package com.jlu.iml;

import com.jlu.mcloud.communicate.heartbeat.Command;
import com.jlu.mcloud.communicate.heartbeat.HeartbeatHandler;
import com.jlu.mcloud.communicate.heartbeat.HeartbeatPacket;
import com.jlu.utils.Const;
import com.jlu.utils.DBManager;
import com.jlu.utils.MySqlDB;

import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Author freedom
 * @DATE 2017/5/16 0016 21:50.
 * see   心跳包接口实现类
 */
public class HeartBeatHandlerImpl implements HeartbeatHandler {
    private static final Logger log = Logger.getLogger(HeartBeatHandlerImpl.class.getName());
    @Override
    public Command sendHeartbeat(HeartbeatPacket heartbeatPacket) throws ConnectException {
        String deviceID = heartbeatPacket.getNodeId();//获取手机序列号
        Map<String, Object> info = heartbeatPacket.getInfo();
        /*获取手机参数*/
        String totalMemory = info.get(Const.TAG_TOTAL_MEMORY).toString();
        String availMemory = info.get(Const.TAG_AVAIL_MEMORY).toString();
        String threshold = info.get(Const.TAG_THRESHOLD).toString();
        String isLowMemory = info.get(Const.TAG_IS_LOWMEMORY).toString();
        String leftPower = info.get(Const.TAG_LEFT_POWER).toString();
        String cpuFrequency = info.get(Const.TAG_CPU_FREQUENCY).toString();
        String ip = info.get(Const.NODE_IP).toString();
        /*存入数据库*/
        boolean flag = DBManager.isExit(deviceID);
        String sql = "";
        if(flag){
            sql = "update infor set total_mem='"+totalMemory+"',avail_mem='"+availMemory+"'," +
                    "threshold='"+threshold+"',is_lowpower='"+isLowMemory+"'," +
                    "left_power='"+leftPower+"',cpu='"+cpuFrequency+"' where dev_id='"+deviceID+"'" ;
        }else{
            sql = "insert into infor(dev_id,total_mem,avail_mem,threshold,is_lowpower,left_power,cpu)" +
                    "values ('"+deviceID+"','"+totalMemory+"','"+availMemory+"','"+threshold+"'," +
                    "'"+isLowMemory+"','"+leftPower+"','"+cpuFrequency+"')";
        }
        int result = MySqlDB.update(sql);
        if(result>0){
            log.info("手机信息存入数据库成功");
        }else {
            log.info("手机信息存入数据库失败");
        }
        System.out.println("id: " + deviceID + "\tip:"+ip+"\tinfo: " + info);
        /*反馈结果*/
        Command command = new Command();
        Map<String, Object> retInfo = new HashMap<String, Object>();
        retInfo.put("ack", Const.SERVER_REPLY);
        command.setInfo(retInfo);
        return command;
    }
}
